import 'dart:ui';

class GraphicCanvas {
  final Canvas _canvas;

  GraphicCanvas(Canvas canvas) : _canvas = canvas;

  GraphicCanvas drawLine(
      Paint paint, double dx1, double dy1, double dx2, double dy2) {
    _canvas.drawLine(Offset(dx1, dy1), Offset(dx2, dy2), paint);
    return this;
  }

  GraphicCanvas drawDashLine(Paint paint, double x1, double y1, double x2,
      double y2, List<double> dashPattern) {
    // 计算两点之间的距离
    double dist = (Offset(x2, y2) - Offset(x1, y1)).distance;
    // 当前已绘制的距离
    double currDist = 0;
    // 用于判断当前是否绘制实线部分
    bool isDashOn = true;

    while (currDist < dist) {
      // 根据当前状态选择虚线部分或实线部分的长度
      double segLength = isDashOn ? dashPattern[0] : dashPattern[1];
      if (currDist + segLength > dist) {
        // 如果剩余距离小于当前部分长度，调整长度以适应剩余距离
        segLength = dist - currDist;
      }

      if (isDashOn) {
        // 计算当前线段的终点坐标
        double endX = x1 + ((x2 - x1) * currDist / dist);
        double endY = y1 + ((y2 - y1) * currDist / dist);

        // 计算下一个线段的终点坐标
        double nextEndX = endX + ((x2 - x1) * segLength / dist);
        double nextEndY = endY + ((y2 - y1) * segLength / dist);

        // 如果当前是实线部分，在画布上绘制线段
        _canvas.drawLine(Offset(endX, endY), Offset(nextEndX, nextEndY), paint);
      }

      // 更新已绘制距离和状态
      currDist += segLength;
      isDashOn = !isDashOn;
    }

    return this;
  }
}
